package com.lb.shopguide.ui.fragment.boss;

import android.graphics.Color;
import android.support.v7.widget.AppCompatSpinner;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseMainFragment;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.event.guide.StartBrotherEvent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.BossMainActivity;
import com.lb.shopguide.ui.view.chart.LbCircleView;
import com.lb.shopguide.ui.view.chart.LbLineView;
import com.lb.shopguide.ui.view.chart.LbMemberLegendLayout;
import com.lb.shopguide.ui.view.chart.LbMemberPercentLayout;
import com.lb.shopguide.ui.view.chart.LbShopDataLayout;
import com.lb.shopguide.ui.view.chart.entity.MemberChartBean;
import com.lb.shopguide.ui.view.chart.entity.MemberPercentBean;
import com.lb.shopguide.ui.view.chart.entity.PerformanceBean;
import com.lb.shopguide.ui.view.chart.entity.ShopDataBean;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.ChartUtil;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnMultiPurposeListener;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;

/**
 * Created by kang on 2017/12/25.
 * 数据概览
 */

public class FragmentDataOverview extends BaseMainFragment {
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    //业绩
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.tv_manager_num)
    TextView tvManagerNum;
    @BindView(R.id.tv_store_num)
    TextView tvStoreNum;
    @BindView(R.id.tv_guide_num)
    TextView tvGuideNum;
    @BindView(R.id.tv_all_performance)
    TextView tvAllPerformance;
    @BindView(R.id.layout_shop_data)
    LinearLayout layoutShopData;
    @BindView(R.id.spi_date)
    AppCompatSpinner spinner;
    //会员
    @BindView(R.id.tv_member_count)
    TextView tvMemberCount;
    @BindView(R.id.tv_new_member_count)
    TextView tvNewMemberCount;
    @BindView(R.id.tv_active_member_count)
    TextView tvActiveMemberCount;
    @BindView(R.id.tv_active_member_state)
    TextView tvActiveMemberState;
    @BindView(R.id.layout_pie_empty)
    LinearLayout layoutEmpty;
    //会员占比
    @BindView(R.id.layout_member_percent)
    LinearLayout layoutMemberPercent;
    @BindView(R.id.layout_member_legend)
    LinearLayout layoutMemberLegend;
    @BindView(R.id.layout_whole_member_percent)
    LinearLayout layoutWholeMemberPercent;
    @BindView(R.id.chart_line)
    LbLineView lineChart;
    @BindView(R.id.chart_pie)
    LbCircleView pieChart;

    private MaterialHeader mMaterialHeader;

//    private String[] dateTypeArray;



    public static FragmentDataOverview newInstance() {
        return new FragmentDataOverview();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_data_overview;
    }

    @Override
    public void initData() {
        initRequest();
    }

    @Override
    public void initView() {
        mMaterialHeader = (MaterialHeader) refreshLayout.getRefreshHeader();
//        refreshLayout.setEnableHeaderTranslationContent(true);
        refreshLayout.setEnableOverScrollDrag(false);
        spinner.setSelection(1, true);//默认30天的选项

        initListener();
    }

    @Override
    public void finishRefresh() {
        refreshLayout.finishRefresh();
    }

    @Override
    public void sessionOutOfDate() {
        ((BossMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
        finishRefresh();
    }

    private void initRequest() {
        sendRequestGetMerchantStaticInfo();
        sendRequestGetPerformanceData(AppConstant.CHART_30_DAY);
        sendRequestGetMemberData();
        sendRequestGetMemberPercentData();
    }

    private void initListener() {
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                if (position == 0) {
                    sendRequestGetPerformanceData(AppConstant.CHART_RECENT_7_DAY);
                } else if (position == 1) {
                    sendRequestGetPerformanceData(AppConstant.CHART_30_DAY);
                } else if (position == 2) {
                    sendRequestGetPerformanceData(AppConstant.CHART_THIS_YEAR);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        refreshLayout.setOnRefreshListener(new OnMultiPurposeListener() {
            @Override
            public void onHeaderPulling(RefreshHeader header, float percent, int offset, int headerHeight, int extendHeight) {

            }

            @Override
            public void onHeaderReleased(RefreshHeader header, int headerHeight, int extendHeight) {

            }

            @Override
            public void onHeaderReleasing(RefreshHeader header, float percent, int offset, int headerHeight, int extendHeight) {

            }

            @Override
            public void onHeaderStartAnimator(RefreshHeader header, int headerHeight, int extendHeight) {

            }

            @Override
            public void onHeaderFinish(RefreshHeader header, boolean success) {

            }

            @Override
            public void onFooterPulling(RefreshFooter footer, float percent, int offset, int footerHeight, int extendHeight) {

            }

            @Override
            public void onFooterReleased(RefreshFooter footer, int footerHeight, int extendHeight) {

            }

            @Override
            public void onFooterReleasing(RefreshFooter footer, float percent, int offset, int footerHeight, int extendHeight) {

            }

            @Override
            public void onFooterStartAnimator(RefreshFooter footer, int footerHeight, int extendHeight) {

            }

            @Override
            public void onFooterFinish(RefreshFooter footer, boolean success) {

            }

            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {

            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                initRequest();
            }

            @Override
            public void onStateChanged(RefreshLayout refreshLayout, RefreshState oldState, RefreshState newState) {

            }
        });
    }

    private void sendRequestGetMerchantStaticInfo() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JSONObject jsonObject = JsonUtil.getJsonObjectFromMap(response.getReturnContent());
                    try {
                        String accumulatedIncome = jsonObject.getString("accumulatedIncome");
                        int storeNum = 0;
                        if (jsonObject.has("storeNum")) {
                            storeNum = jsonObject.getInt("storeNum");
                        }
                        int staffNum = 0;
                        if (jsonObject.has("staffNum")) {
                            staffNum = jsonObject.getInt("staffNum");
                        }
                        int shopkeeperNum = 0;
                        if (jsonObject.has("shopkeeperNum")) {
                            shopkeeperNum = jsonObject.getInt("shopkeeperNum");
                        }
                        bindBaseMerchantData(accumulatedIncome, storeNum, staffNum, shopkeeperNum);
                        refreshLayout.finishRefresh(1000);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        ApiMethodBoss.getMerchantStaticInfo(new SimpleLbObserver(listener, otherListener),this,FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetPerformanceData(int dateType) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JSONObject jsonObject = JsonUtil.getJsonObjectFromMap(response.getReturnContent());
                    try {
                        PerformanceBean merchantPerformance = JsonUtil.getGson().fromJson(jsonObject.getString("merchantPerformance"), PerformanceBean.class);
                        // 线图
                        drawLineChart(merchantPerformance);
                        if (jsonObject.has("storePerformance")) {
                            PerformanceBean storePerformance = JsonUtil.getGson().fromJson(jsonObject.getString("storePerformance"), PerformanceBean.class);
                            // 门店数据
                            bindShopData(storePerformance);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        ApiMethodBoss.getPerformanceData(new SimpleLbObserver(listener, otherListener), dateType,this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetMemberData() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    MemberChartBean memberChartBean = (MemberChartBean) JsonUtil.getObject(response.getReturnContent(), MemberChartBean.class);
                    bindMemberData(memberChartBean.getTotalMemberNum(), memberChartBean.getNewMemberNum(), memberChartBean.getActiveMemberNum(),
                            memberChartBean.getActivePercent(), memberChartBean.getActiveFlag());
                    drawPieChart(memberChartBean.getMemberQuality());
                }
            }

        };
        ApiMethodBoss.getMemberData(new SimpleLbObserver(listener, otherListener),this,FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetMemberPercentData() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    PerformanceBean memberPercentBean = (PerformanceBean) JsonUtil.getObject(response.getReturnContent(), PerformanceBean.class);
                    bindMemberPercent(memberPercentBean);
                }
            }

        };
        ApiMethodBoss.getStoreMemberProportion(new SimpleLbObserver(listener, otherListener),this,FragmentEvent.DESTROY_VIEW);
    }

    private void bindBaseMerchantData(String allIncome, int storeNum, int staffNum, int shopKeepNum) {
        tvTotalMoney.setText("￥" + allIncome);
        SpannableString sp = new SpannableString(tvTotalMoney.getText().toString());
        sp.setSpan(new RelativeSizeSpan(0.6f), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //0.5f表示
        tvTotalMoney.setText(sp);
        tvStoreNum.setText("" + storeNum);
        tvManagerNum.setText("" + shopKeepNum);
        tvGuideNum.setText("" + staffNum);
    }

    private void drawLineChart(PerformanceBean performanceBean) {
        ChartUtil.bindLineChart(lineChart, performanceBean);
        tvAllPerformance.setText(performanceBean.getTitle().getSubtext());
    }

    private void drawPieChart(PerformanceBean performanceBean) {
        int[] colors = {Color.parseColor("#e9e9e9"), Color.parseColor("#ff6c6c"), Color.parseColor("#ffc23b"), Color.parseColor("#94cdff"), Color.parseColor("#a394ff")};
        if (ChartUtil.bindPieChartInHome(pieChart, performanceBean, colors)) {
            pieChart.setVisibility(View.VISIBLE);
            layoutEmpty.setVisibility(View.GONE);
        } else {
            layoutEmpty.setVisibility(View.VISIBLE);
            pieChart.setVisibility(View.GONE);
        }
    }

    private void bindMemberPercent(PerformanceBean performanceBean) {
        layoutMemberPercent.removeAllViews();
        final ArrayList<MemberPercentBean> list = ChartUtil.getMemberPercentList(performanceBean);
        int size = list.size();
        if (size == 0) {
            layoutWholeMemberPercent.setVisibility(View.GONE);
        } else {
            layoutWholeMemberPercent.setVisibility(View.VISIBLE);
        }
        if (size > 3) {
            size = 3;
        }
        for (int i = 0; i < size; i++) {
            LbMemberPercentLayout lbMemberPercentLayout = new LbMemberPercentLayout(mContext);
            lbMemberPercentLayout.setMemberPercentBean(list.get(i), i);
            layoutMemberPercent.addView(lbMemberPercentLayout);
            if (i == 2 && i < list.size() - 1) {
                lbMemberPercentLayout.showMore();
                lbMemberPercentLayout.setOnShowMoreListener(new LbMemberPercentLayout.OnShowMoreListener() {
                    @Override
                    public void showMore() {
                        EventBus.getDefault().post(new StartBrotherEvent(FragmentAllMemberPercent.newInstance(list)));
                    }
                });
            }
        }
    }

    private void bindShopData(PerformanceBean performanceBean) {
        layoutShopData.removeAllViews();
        final ArrayList<ShopDataBean> list = ChartUtil.getShopDataList(performanceBean);
        if (layoutShopData.getChildCount() == 0) {
            int size = list.size();
            if (size > 3) {
                size = 3;
            }
            for (int i = 0; i < size; i++) {
                LbShopDataLayout lbShopDataLayout = new LbShopDataLayout(mContext);
                lbShopDataLayout.setShopData(list.get(i), i);
                layoutShopData.addView(lbShopDataLayout);
                if (i == 2 && i < list.size() - 1) {
                    lbShopDataLayout.showMore();
                    lbShopDataLayout.setOnShowMoreListener(new LbShopDataLayout.OnShowMoreListener() {
                        @Override
                        public void showMore() {
                            EventBus.getDefault().post(new StartBrotherEvent(FragmentAllShopData.newInstance(list)));
                        }
                    });
                }
            }
        }
    }

    private void bindMemberData(int memberCount, int newCount, int activeCount, String percent, int flag) {
        tvMemberCount.setText("" + memberCount);
        tvNewMemberCount.setText("" + newCount);
        int decreaseColor = Color.rgb(255, 102, 102);
        int increaseColor = Color.rgb(102, 183, 255);
        tvActiveMemberCount.setText("" + activeCount);
        if (flag == AppConstant.ACTIVE_MEMBER_INCREASE_FLAG) {
            tvActiveMemberCount.setTextColor(increaseColor);
            tvActiveMemberState.setTextColor(increaseColor);
            tvActiveMemberState.setText("↑" + percent);

            SpannableString sp = new SpannableString(tvActiveMemberState.getText().toString());
            sp.setSpan(new RelativeSizeSpan(1.3f), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //0.5f表示
            tvActiveMemberState.setText(sp);
        } else if (flag == AppConstant.ACTIVE_MEMBER_DEUCE_FLAG) {
            tvActiveMemberCount.setTextColor(increaseColor);
            tvActiveMemberState.setTextColor(increaseColor);
            tvActiveMemberState.setText("- 持平");
        } else if (flag == AppConstant.ACTIVE_MEMBER_DECREASE_FLAG) {
            tvActiveMemberCount.setTextColor(decreaseColor);
            tvActiveMemberState.setTextColor(decreaseColor);
            tvActiveMemberState.setText("↓" + percent);

            SpannableString sp = new SpannableString(tvActiveMemberState.getText().toString());
            sp.setSpan(new RelativeSizeSpan(1.3f), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //0.5f表示
            tvActiveMemberState.setText(sp);
        }
        bindMemberLegend();
    }

    private void bindMemberLegend() {
        if (layoutMemberLegend.getChildCount() == 0) {
            for (int i = 1; i < 4; i++) {
                LbMemberLegendLayout legendLayout = new LbMemberLegendLayout(mContext);
                legendLayout.setLine(i);
                layoutMemberLegend.addView(legendLayout);
            }
        }
    }


    @Override
    public String getPageTag() {
        return FragmentDataOverview.class.getName();
    }

}
